import com.mysql.cj.jdbc.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

//增删改
public class DEMO1 {
    public static void main(String[] args) throws SQLException {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入学号:");
        int id  = scanner.nextInt();
        System.out.println("请输入姓名:");
        String name  = scanner.next();

        //1.创建一个datasource
        DataSource dataSource = new MysqlDataSource();

        ((MysqlDataSource) dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/java109?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource) dataSource).setUser("root");
        ((MysqlDataSource) dataSource).setPassword("123456");


        //2.建立与数据库服务器之间的连接
        Connection connection = dataSource.getConnection();


        //3.构造一个sql，(代码中的sql不需要写分号)PreparedStatement对象，用于执行预编译的 SQL 语句
        String sql = "insert into student values(?,?)";
        PreparedStatement statement =connection.prepareStatement(sql);
        statement.setInt(1,id);
        statement.setString(2,name);


        //4.把sql发给服务器,返回值是一个整数，表示影响到的行数 update是写操作,包括增删改
        int n = statement.executeUpdate();
        System.out.println("n =" + n);


        //5.释放资源，关闭连接 释放的顺序：后获取的先释放
        statement.close();
        connection.close();
    }
}
